<template>
  <div class="sys-org-container">

      <div style="width: 100%;">
        <screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData">
          <el-button @click="openAddOrg" type="primary">新建盘点任务</el-button>
        </screeningCondition>
      </div>

        <el-card class="full-table" shadow="hover" style="margin-top: 5px">
          <el-table :data="state.Data" v-loading="state.loading" row-key="id" default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border highlight-current-row
            :header-cell-style="{
              background: 'var(--el-color-primary)',
              height: '55px',
              color: '#fff',
              border: '1px solid #fff',
              fontWeight: 'bold',
              fontSize: '13px',
            }" :cell-style="{ padding: '2px' }" class="el-table">
            <el-table-column type="index" label="序号" align="center"></el-table-column>

            <el-table-column prop="takeStockNum" label="盘点编号" align="center" show-overflow-tooltip />
            <el-table-column prop="materielNum" label="物料号" align="center" show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.materielNum">{{ scope.row.materielNum }}</span>
                <span v-else>暂无编号</span>
              </template>
            </el-table-column>

            <el-table-column prop="takeStockType" label="盘点类别" align="center" show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.takeStockType == 1">库位盘点</span>
                <span v-else>物料盘点</span>
              </template>
            </el-table-column>
            <el-table-column prop="takeStockTime" label="任务创建时间" align="center" show-overflow-tooltip>

            </el-table-column>
            <el-table-column prop="takeStockStorageNum" label="盘点库位" align="center" show-overflow-tooltip />
            <el-table-column prop="takeStockStatus" label="盘点状态" align="center" show-overflow-tooltip>
              <template v-slot="scope">
                <el-tag type="warning" v-if="scope.row.takeStockStatus == 0">待盘点</el-tag>
                <el-tag type="success" v-else>已盘点</el-tag>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.pageSize"
            :page-sizes="[20, 30, 40, 50]" layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
        </el-card>
  


    <el-drawer v-model="addDrawer" :append-to-body="true" size="30%">
      <div style="display: flex; justify-content: center; margin-top: 30px">
        <el-button type="primary" round @click="handleButtonClick" style="width: 100px; height: 30px">按物料盘点</el-button>
        <el-button type="primary" round @click="handleButtonClick2" style="width: 100px; height: 30px">按库位盘点</el-button>
      </div>
      <!-- 按物料盘点 -->
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" class="fl"
        v-if="showModel1 && showModel2 == false">
        <el-form-item label="物料号" prop="materielnum" :rules="[{ required: true, message: '物料号不能为空', trigger: 'blur' }]"
          @click="open">
          <el-input v-model="state.ruleForm.materielnum"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按库位盘点 -->
      <el-form :model="state.ruleForm" ref="ruleformRef" label-width="auto" class="fl"
        v-if="showModel2 && showModel1 == false">
        <el-form-item label="所属仓库" :rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.whNum" filterable clearable class="w100"
            @change="handleChange(state.ruleForm.whNum)">
            <el-option v-for="item in state.belongWarehouses" :key="item" :label="item.eg_wms_warehouse.WHName"
              :value="item.eg_wms_warehouse.WHNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" prop="regionNum" :rules="[{ required: true, message: '所属区域不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.regionNum" filterable clearable class="w100"
            @change="handleRegionchange()">
            <el-option v-for="item in state.belongAreas" :key="item" :label="item.RegionName" :value="item.RegionNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位编号" prop="storageNum" :rules="[{ required: true, message: '库位编号不能为空', trigger: 'blur' }]"
          @click="openAdd">
          <el-input v-model="state.ruleForm.storageNum" type="textarea" clearable />
        </el-form-item>
      </el-form>
      <div style="width: 100%; display: flex; justify-content: center; margin-top: 60px">
        <el-button @click="submit" type="primary" round style="width: 80px; height: 30px">确认</el-button>
        <el-button @click="addDrawer = false" round style="width: 80px; height: 30px">取消</el-button>
      </div>
    </el-drawer>
    
    <EditPos ref="editPosRef" :title="state.editPosTitle" @handleQuery="getData" />
  </div>
</template>

<script lang="ts" setup name="sysOrg">
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import EditWuliao from "/@/views/system/takeInventory/editWuliao.vue";
import EditOrg from "/@/views/system/takeInventory/editKuwei.vue";
import { getAPI } from "/@/utils/axios-utils";
import { WmsApi } from "/@/api/wh";
import screeningCondition from "/@/views/tools/screeningCondition.vue";
import { feature } from "/@/utils/axios-utils";
import { APIJSONApi } from "/@/api-services/apis/apijsonapi";
import EditPos from '/@/views/system/takeInventory/component copy/editPos.vue';

const editPosRef=ref()
const ruleFormRef = ref();
const ruleformRef = ref();
const waitFormRef = ref();
const showModel1 = ref(false);
const showModel2 = ref(false);
const addDrawer = ref(false);
const editRef = ref();
const editRef2 = ref();
const waitTakeDrawer = ref(false);
const state = reactive({
  editPosTitle:'',
  loading: false,
  Data: [], // 机构列表数据
  queryParams: {
    page: 1,
    pageSize: 20,
  },
  editOrgTitle: "",
  ruleForm: {
    regionNum: "",
    whNum: "",
    storageNum: "",
    materielNum: "",
  },
  ruleForm2: {},
  total: 0,
  WarehousesList: [],
  belongAreas: [],
  belongStorage: [],
  materialList: [],
  inquireInfo: [
    {
      label: "盘点状态",
      value: "",
      key: "takeStockStatus",
      options: [
        {
          value: 1,
          label: "已盘点",
        },
        {
          value: 0,
          label: "待盘点",
        },
      ],
      type: "select",
    },

    {
      label: "盘点类型",
      value: "",
      key: "takeStockType",
      options: [
        {
          value: 0,
          label: "物料盘点",
        },
        {
          value: 1,
          label: "库位盘点",
        },
      ],
      type: "select",
    },
    {
      label: "物料号",
      value: "",
      key: "materielNum",
      options: [],
      type: "input",
    }
  ],
  //保留筛选条件
  value: {}
});

onMounted(async () => {
  try {
    const res = await feature(
      getAPI(APIJSONApi).apiAPIJSONGetPost({
        "[]": {
          eg_wms_warehouse: {
            IsDelete: 0,
            "@column": "WHName,WHNum",
          },
        },
      })
    );
    state.belongWarehouses = res[1].data.result["[]"];
  } catch (error) {
    console.log(error);
  }

  getData(state.queryParams);
});
// 打开新增页面
const openAddOrg = () => {
	// state.ruleForm2 = {};
	// addDrawer.value = true;
	state.editPosTitle = '添加盘点任务';
	editPosRef.value?.openDialog(state.ruleForm);
};
const addValue = (parms) => {
  console.log("我是父组件，我接收到了 " + parms);
  // 处理得到的参数
  let storageNum1 = parms.map((item) => {
    return item.storageNum;
  });
  state.ruleForm.storageNum = storageNum1.join();
  console.log(state.ruleForm.storageNum);
};
const addMaterialValue = (parms) => {
  //得到的参数是一整个对象,拿出物料号
  state.ruleForm.materielnum = parms.map((item) => {
    return item.materielNum;
  });
};

const submit = () => {
  if (state.ruleForm.storageNum) {
    ruleformRef?.value.validate(async (valid, object) => {
      if (!valid) return false;
      WmsApi()
        .CreateTaskByStorage(state.ruleForm.storageNum, "1")
        .then(function (res) {
          addDrawer.value = false;
          ElMessage.success("新增按库位盘点任务成功");
          getData(state.queryParams)
        })
        .catch(function (error) {
          console.log(error);
        });
    });
  } else {
    ruleFormRef?.value.validate(async (valid, object) => {
      if (!valid) return false;
      WmsApi()
        .CreateTaskByMaterial({ materielNum: state.ruleForm.materielnum[0] })

        .then(function (res) {
          console.log(res);
          addDrawer.value = false;
          ElMessage.success("新增按物料盘点任务成功");
          getData(state.queryParams)
        })
        .catch(function (error) {
          console.log(error);
        });
    });
  }

};

// 按物料盘点
const handleButtonClick = () => {
  showModel1.value = true;
  showModel2.value = false;
};
// 按库位盘点
const handleButtonClick2 = () => {
  showModel2.value = true;
  showModel1.value = false;
};
const handleChange = async (id) => {
  state.belongAreas = []; //arr
  try {
    const res = await feature(
      getAPI(APIJSONApi).apiAPIJSONGetPost({
        "[]": {
          eg_wms_region: {
            IsDelete: 0,
            WHNum: id,
            "@column": "RegionNum,RegionName",
          },
        },
      })
    );

    res[1].data.result["[]"].forEach((item, index, input) => {
      input[index] = item.eg_wms_region;
    });
    state.belongAreas = res[1].data.result["[]"];
  } catch (error) {
    console.log(error);
  }
};
const handleRegionchange = () => {
  state.ruleForm.storageNum = ''
}
// 查询操作
const getData = (value) => {
  //把筛选条件保留
  state.value = value;
  console.log(value);
  var params = {
    page: state.queryParams.page,
    pageSize: state.queryParams.pageSize,
    materielNum: value?.materielNum,
    takeStockStatus: value?.takeStockStatus,
    takeStockType: value?.takeStockType,
  };
  WmsApi()
    .TakeInventoryTask(
      JSON.stringify(params)
    )
    .then(function (res) {
      state.Data = res.data.result.items;
      state.total = res.data.result.total;
    })
    .catch(function (error) {
      console.log(error);
    });
};

const submitTake = () => {
  // axios.get(`/api/eGTakeStock/updateTakeStockMessageStatus/` + state.ruleForm2.takestocknum + `/` + state.ruleForm2.takestockcount)
  // 	.then(function (res) {
  // 		console.log(res);
  // 		state.Data = res.data.result.items;
  // 		state.total = res.data.result.total;
  // 	})
  // 	.catch(function (error) {
  // 		console.log(error);
  // 	});
};

// 删除
const delOrg = (row) => {
  ElMessageBox.confirm(`确定删除机构：【${row.name}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await getAPI(SysOrgApi).apiSysOrgDeletePost({ id: row.id });
      ElMessage.success("删除成功");
      getData(state.queryParams);
    })
    .catch(() => { });
};
const handleSizeChange = (val) => {
  state.queryParams.pageSize = val;

  state.queryParams.materielNum = state.value?.materielNum;
  state.queryParams.productionDate = state.value?.productionDate;
  getData(state.queryParams);
};
const handleCurrentChange = (newVal) => {
  state.queryParams.page = newVal;

  state.queryParams.materielNum = state.value?.materielNum;
  state.queryParams.productionDate = state.value?.productionDate;
  getData(state.queryParams);
};
const openAdd = () => {
  state.editOrgTitle = "选取库位";
  editRef.value?.openDialog();
};
const open = () => {
  state.editOrgTitle = "选取物料";
  editRef2.value?.openDialog();
};
</script>
<style lang="scss" scoped>
.fl {
  width: 60%;
  margin: 20px 80px;
}
.container {
    margin-top: 15px;
    width: 100%;
    display: flex;
    flex-direction: column;
    height: calc(100% - 82px);
}

.table {
    width: 100%;
    flex: 1;
    height: 100%;
}

.el-table {
    width: 100%;
}

.extra {
    width: 170px;
    height: 80px;

    :deep(.el-textarea__inner) {
        height: 80px;
    }
}
</style>
